package com.eyas.im.server.nio.handler;

import com.eyas.im.protocol.decoder.Decoder;
import com.eyas.im.protocol.encoder.Encoder;
import com.eyas.im.protocol.protocol.StringProtocol;
import com.eyas.im.server.TaskCompleteFuture;
import com.eyas.im.server.WriteCallbackFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConsoleServerHandler extends AbstractNioServerSocketHandler<StringProtocol> {
    private final static Logger logger = LoggerFactory.getLogger(ConsoleServerHandler.class);
    private ConsoleThread consoleThread;
    private volatile boolean validFlag = true;

    public ConsoleServerHandler(Encoder<StringProtocol> encoder, Decoder<StringProtocol> decoder, int bufferCapacity) {
        super(encoder, decoder, bufferCapacity);
    }

    @Override
    public void afterDecodeData(StringProtocol decodeData) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (decodeData != null && decodeData.getMessage() != null) {
            decodeData.getMessage().forEach(msg -> {
                stringBuilder.append("[").append(msg).append("]");
            });
        }
        System.out.println("客户端说:" + stringBuilder.toString());
    }

    @Override
    public void afterAccept(SocketAddress socketAddress) {
        //这里我们打开一个线程，用于在console可以写数据
        this.consoleThread = new ConsoleThread();
        this.consoleThread.setDaemon(false);
        this.consoleThread.start();
    }

    @Override
    public void beforeClose() {
        //关闭读取console写入的数据的线程
        validFlag = false;
        this.consoleThread.interrupt();
    }

    private class ConsoleThread extends Thread {

        @Override
        public void run() {
            InputStream inputStream = System.in;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String lineStr = null;
            try {
                System.err.print("请输入>>>:");
                while (!(lineStr = bufferedReader.readLine()).equals("bye") && ConsoleServerHandler.this.validFlag) {
                    logger.info("server端获取到控制台输入:{}", lineStr);
                    TaskCompleteFuture taskCompleteFuture = ConsoleServerHandler.this.write(new StringProtocol(lineStr+"\n"), new WriteCallbackFunction() {
                        @Override
                        public void callback(Throwable exception) {
                            if (exception != null) {
                                System.err.println("[发送失败]");
                            } else {
                                System.err.println("[发送成功]");
                            }
                        }
                    });
                    ConsoleServerHandler.this.flush();
//                    taskCompleteFuture.sync();
                    System.err.println("请输入>>>:");
                }
                logger.info("退出当前控制台");
                if (ConsoleServerHandler.this.validFlag) //因为输入bye退出的情况，需要主动关闭通信通道
                    ConsoleServerHandler.this.shutdown();
            } catch (IOException /*| InterruptedException*/ e) {
                e.printStackTrace();
            }
        }
    }
}
